/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.home.gui;

import com.home.common.Constants;
import com.home.common.LevelSubject;
import com.home.components.ModalJInternalFrame;
import com.home.logic.SubjectLogic;
import com.home.mapping.Subject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.DefaultListModel;
import javax.swing.JList;

/**
 *
 * @author vi
 */
public class SubjectChooser extends ModalJInternalFrame {
    
    private Map<Integer,List<Subject>> mapAllSubjects = new TreeMap<>();
    private AgentScorecard agentScorecardScreeen;
    private Subject slSubjectLv1;
    private Subject slSubjectLv2;
    private Subject slSubjectLv3;
    /**
     * Creates new form SubjectChooser
     */
    public SubjectChooser(AgentScorecard agentScorecardScreeen, Subject subject) {
        initComponents();
        
        this.agentScorecardScreeen = agentScorecardScreeen;
        
        int width = this.getWidth() - 60;
        
        splitPane1.setDividerLocation(width / 3);
        splitPane2.setDividerLocation(width / 3);
        settingStatusOfListLevel(true, false, false);
        
        btnChoose.setEnabled(false);
        
        loadData();
        if (subject.getLevel() != null) {
            if (subject.getLevel().compareTo(LevelSubject.SUBJECT_LEVEL_3) == 0) {
                List<Subject> listSubjectCurrentLevel = mapAllSubjects.get(subject.getLevel());
                for (Subject sub : listSubjectCurrentLevel) {
                    if (sub.getIdSubject().compareTo(subject.getIdSubject()) == 0) {
                        slSubjectLv3 = sub;
                    }            
                }
                
                slSubjectLv2 = getParentOfChild(subject.getIdParent(), subject.getLevel());
                slSubjectLv1 = getParentOfChild(slSubjectLv2.getIdParent(), slSubjectLv2.getLevel());
                listLevel1.setSelectedValue(slSubjectLv1, true);
                listLevel2.setModel(getModelNextLevel(listLevel1, new Integer(1)));
                listLevel2.setSelectedValue(slSubjectLv2, true);
                listLevel3.setModel(getModelNextLevel(listLevel2, new Integer(2)));
                listLevel3.setSelectedValue(slSubjectLv3, true);
                settingStatusOfListLevel(true, true, true);
            } else if (subject.getLevel().compareTo(LevelSubject.SUBJECT_LEVEL_2) == 0) {           
                List<Subject> listSubjectCurrentLevel = mapAllSubjects.get(subject.getLevel());
                for (Subject sub : listSubjectCurrentLevel) {
                    if (sub.getIdSubject().compareTo(subject.getIdSubject()) == 0) {
                        slSubjectLv2 = sub;
                    }            
                }
                
                slSubjectLv1 = getParentOfChild(slSubjectLv2.getIdParent(), slSubjectLv2.getLevel());
                listLevel1.setSelectedValue(slSubjectLv1, true);
                listLevel2.setModel(getModelNextLevel(listLevel1, new Integer(1)));
                listLevel2.setSelectedValue(slSubjectLv2, true);
                settingStatusOfListLevel(true, true, false);
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        levelPanel = new javax.swing.JPanel();
        splitPane1 = new javax.swing.JSplitPane();
        splitPane2 = new javax.swing.JSplitPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        listLevel2 = new javax.swing.JList();
        jScrollPane3 = new javax.swing.JScrollPane();
        listLevel3 = new javax.swing.JList();
        jScrollPane1 = new javax.swing.JScrollPane();
        listLevel1 = new javax.swing.JList();
        jPanel5 = new javax.swing.JPanel();
        btnChoose = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();

        setClosable(true);
        setTitle("Choose Subject");
        setMinimumSize(new java.awt.Dimension(800, 500));
        setPreferredSize(new java.awt.Dimension(800, 500));

        levelPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Level"));

        listLevel2.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listLevel2ValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(listLevel2);

        splitPane2.setLeftComponent(jScrollPane2);

        listLevel3.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listLevel3ValueChanged(evt);
            }
        });
        jScrollPane3.setViewportView(listLevel3);

        splitPane2.setRightComponent(jScrollPane3);

        splitPane1.setRightComponent(splitPane2);

        listLevel1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listLevel1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(listLevel1);

        splitPane1.setLeftComponent(jScrollPane1);

        javax.swing.GroupLayout levelPanelLayout = new javax.swing.GroupLayout(levelPanel);
        levelPanel.setLayout(levelPanelLayout);
        levelPanelLayout.setHorizontalGroup(
            levelPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(splitPane1)
        );
        levelPanelLayout.setVerticalGroup(
            levelPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(splitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE)
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Command"));

        btnChoose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/btn_ok.png"))); // NOI18N
        btnChoose.setText("Choose");
        btnChoose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChooseActionPerformed(evt);
            }
        });

        btnCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/btn_cancel.png"))); // NOI18N
        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap(378, Short.MAX_VALUE)
                .addComponent(btnCancel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnChoose)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnChoose)
                    .addComponent(btnCancel))
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(levelPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(levelPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void listLevel1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listLevel1ValueChanged
        slSubjectLv1 = (Subject)listLevel1.getSelectedValue();
        listLevel3.setListData(new Object[0]);
        listLevel2.clearSelection();
        listLevel3.clearSelection();
        listLevel2.setModel(getModelNextLevel(listLevel1, new Integer(1)));
        settingStatusOfListLevel(true, true, false);
        btnChoose.setEnabled(false);
    }//GEN-LAST:event_listLevel1ValueChanged

    private void listLevel2ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listLevel2ValueChanged
        slSubjectLv2 = (Subject)listLevel2.getSelectedValue();
        listLevel3.clearSelection();
        DefaultListModel model = getModelNextLevel(listLevel2, new Integer(2));
        if (model.isEmpty()) {
            btnChoose.setEnabled(true);
        } else {
            btnChoose.setEnabled(false);
        }
        listLevel3.setModel(model);
        settingStatusOfListLevel(true, true, true);
        
    }//GEN-LAST:event_listLevel2ValueChanged

    private void btnChooseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChooseActionPerformed
        Subject selectedSubjectLv2 = (Subject)listLevel2.getSelectedValue();
        if (getModelNextLevel(listLevel2, new Integer(2)).isEmpty()) {
            agentScorecardScreeen.setSelectedSubject(selectedSubjectLv2);
            agentScorecardScreeen.txtSubject.setText(slSubjectLv1.getSubject() + Constants.SEPARATOR_SUBJECT_LEVEL +slSubjectLv2.getSubject());
        } else {
            Subject selectedSubjectLv3 = (Subject)listLevel3.getSelectedValue();
            agentScorecardScreeen.setSelectedSubject(selectedSubjectLv3);
            agentScorecardScreeen.txtSubject.setText(slSubjectLv1.getSubject() + Constants.SEPARATOR_SUBJECT_LEVEL +slSubjectLv2.getSubject() + Constants.SEPARATOR_SUBJECT_LEVEL + slSubjectLv3.getSubject());
        }
        this.dispose();
    }//GEN-LAST:event_btnChooseActionPerformed

    private void listLevel3ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listLevel3ValueChanged
        slSubjectLv3 = (Subject)listLevel3.getSelectedValue();
        btnChoose.setEnabled(true);
    }//GEN-LAST:event_listLevel3ValueChanged

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnChoose;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JPanel levelPanel;
    private javax.swing.JList listLevel1;
    private javax.swing.JList listLevel2;
    private javax.swing.JList listLevel3;
    private javax.swing.JSplitPane splitPane1;
    private javax.swing.JSplitPane splitPane2;
    // End of variables declaration//GEN-END:variables

    private void settingStatusOfListLevel(boolean level1, boolean level2, boolean level3) {
        listLevel1.setEnabled(level1);
        listLevel2.setEnabled(level2);
        listLevel3.setEnabled(level3);
    }
    private List<Subject> filterListChild(List<Subject> list, Integer idParent) {
        List<Subject> listFiltered = new ArrayList<>();
        for (Subject subject : list) {
            if (subject.getIdParent().compareTo(idParent) == 0) {
                listFiltered.add(subject);
            }            
        }       
        return listFiltered;
    }
    
    private Subject getParentOfChild(Integer parentId, Integer currentLevel) {
        Subject parent = new  Subject();
        List<Subject> listSubjectNextLevel = mapAllSubjects.get(currentLevel - 1);
        for (Subject subject : listSubjectNextLevel) {
            if (subject.getIdSubject().compareTo(parentId) == 0) {
                parent = subject;
            }            
        }
        return parent;
    }
        
    
    private void loadData() {
        // get all subjects
        mapAllSubjects = new SubjectLogic().findMapAllLevelAndChilds();
        
        DefaultListModel model1 = new DefaultListModel();
        for (Subject subject : mapAllSubjects.get(LevelSubject.SUBJECT_LEVEL_1)) {
            model1.addElement(subject);
        }        
        listLevel1.setModel(model1);
    }
    
    private List<Subject> getChildNextLevel(Integer currentLevel, Integer idParent) {
        List<Subject> listSubjectNextLevel = mapAllSubjects.get(currentLevel + 1);
        return filterListChild(listSubjectNextLevel, idParent);      
    }
    
    private DefaultListModel getModelNextLevel(JList listLevel, Integer currentLevel) {
        Subject selectedSubject = (Subject)listLevel.getSelectedValue();
        DefaultListModel model = new DefaultListModel();
        if (selectedSubject != null) {
            List<Subject> listChild = getChildNextLevel(currentLevel, selectedSubject.getIdSubject());           
            for (Subject subject : listChild) {
                model.addElement(subject);
            }           
        }
        return model;
    }
}
